#!/usr/bin/env python

import xlwt
import component

from autorm.fields import *

class Sms(component.Model):
    '''Sms class
    
    @author Julot <andy.julot@gmail.com>
    @since Wednesday, February 15, 2012. 03:47 PM'''
    
    class Meta:
        table = 'sms'
        pk = 'id'
        fields = [IdField('id'),
                  ISODateTimeField('insertTime'),
                  ISODateTimeField('updateTime'),
                  ISODateTimeField('dateTime', index=True),
                  IntegerField('total', index=True),
                  IntegerField('sequence'),
                  IntegerField('reference'),
                  BoolField('decompiled', index=True, default=0),
                  BoolField('deleted', index=True, default=0),
                  BoolField('archived', index=True, default=0),
                  BoolField('read', index=True, default=0),
                  ISODateTimeField('deleteTime'),
                  TextField('number', 255),
                  TextField('pdu'),
                  TextField('message')]
    
    @property
    def completeMessage(self):
        if self.total == 1: return self.message
        
        timedelta = datetime.timedelta(minutes=10)
        query = Sms.objects.query(reference=self.reference, number=self.number,
                                  sequence__gt=1,
                                  dateTime__gte=self.dateTime - timedelta)
        query.order_by('sequence')
        sequence = 1
        message = self.message
        for q in query:
            sequence += 1
            if q.sequence != sequence:
                message += "\r\n...\r\n"
            else:
                message += q.message
        if sequence < self.total:
            message += "\r\n..."
        return message
    
    @classmethod
    def toExcel(cls, path):
        wb = xlwt.Workbook()
        ws = wb.add_sheet('SMS')
        ws.write(0, 0, 'No')
        ws.write(0, 1, 'Time')
        ws.write(0, 2, 'Number')
        ws.write(0, 3, 'Message')
        
        query = cls.objects.query().order_by('dateTime', 'desc')
        query.filter(decompiled=1, sequence__lt=2)
        
        row = 0
        for q in query:
            row += 1
            ws.write(row, 0, row)
            date = q.dateTime.strftime('%Y-%m-%d %H:%M:%S')
            ws.write(row, 1, date)
            ws.write(row, 2, q.number)
            ws.write(row, 3, q.completeMessage)
            
        wb.save(path)